package cn.kgc.listener;

import cn.kgc.service.MessageInfoService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author YC
 * 从死信队列中获得信息
 * 注解@ConditionalOnProperty(value = "mq.enableHandleDlx") 配置文件中配置mq.enableHandleDlx=true则启用此类
 */
@Component
@ConditionalOnProperty(value = "mq.enableHandleDlx")
public class DeadLetterMessageListener implements ChannelAwareMessageListener {

    private static final Logger log = LoggerFactory.getLogger(DeadLetterMessageListener.class);
    @Resource
    private MessageInfoService messageInfoService;

    /**
     * 消息监听
     *
     * @param message 消息
     * @param channel 通道
     * @throws Exception 异常
     */
    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        // 获取消息相关属性
        String messageId = message.getMessageProperties().getHeader("spring_returned_message_correlation");
        String exchange = message.getMessageProperties().getReceivedExchange();
        String queue = message.getMessageProperties().getConsumerQueue();
        // 将消息状态标记为死亡
        messageInfoService.messageReceiveDead(messageId);
        log.warn("原交换机{}中{}队列的ID为{}的消息多次消费失败，已进入死信队列", exchange, queue, messageId);
        // 从死信队列中删除此条消息
        if (channel != null) {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }

}
